import React, { createContext, useState, useContext, useCallback } from 'react';
import { handleExtensionError } from '../utils/extensionErrorHandler';

const ErrorContext = createContext(null);

/**
 * Provider component for managing application errors
 */
export const ErrorProvider = ({ children }) => {
  const [errors, setErrors] = useState([]);
  
  // Add a new error to the queue
  const addError = useCallback((error) => {
    // Generate a unique ID for the error
    const errorWithId = {
      ...error,
      id: Date.now().toString()
    };
    
    setErrors(prevErrors => [...prevErrors, errorWithId]);
    return errorWithId.id; // Return the ID for reference
  }, []);
  
  // Handle extension-specific errors
  const handleExtError = useCallback((error) => {
    const processedError = handleExtensionError(error);
    return addError(processedError);
  }, [addError]);
  
  // Remove an error by its ID
  const removeError = useCallback((errorId) => {
    setErrors(prevErrors => prevErrors.filter(error => error.id !== errorId));
  }, []);
  
  // Clear all errors
  const clearErrors = useCallback(() => {
    setErrors([]);
  }, []);
  
  // Get the most recent error (for display purposes)
  const currentError = errors.length > 0 ? errors[errors.length - 1] : null;
  
  const value = {
    errors,
    currentError,
    addError,
    handleExtError,
    removeError,
    clearErrors
  };
  
  return (
    <ErrorContext.Provider value={value}>
      {children}
    </ErrorContext.Provider>
  );
};

// Custom hook to use the error context
export const useErrors = () => {
  const context = useContext(ErrorContext);
  if (!context) {
    throw new Error('useErrors must be used within an ErrorProvider');
  }
  return context;
};
